package com.cly.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.cly.common.util.ThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后期通过网关传递用户信息到请求头，拦截下来
 */
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取封装在请求头中的用户信息
        String userInfo = request.getHeader("user-info");

        // 判断用户信息是否存在
        if(StrUtil.isNotBlank(userInfo)){
            // 存在，将用户信息放入线程变量中
            ThreadLocalUtil.set(Long.valueOf(userInfo));
        }

        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
